import { Button } from "@/shared/ui/button"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/shared/ui/form"
import { Input } from "@/shared/ui/input"
import { useToast } from "@/shared/ui/use-toast"
import { useRegisterMutation } from "@/app/auth/authApi"
import { useEffect } from "react"
import { useLocation, useNavigate } from "react-router-dom"

const UsernameSchema = z.object({
  username: z.string({ required_error: "Обязательное поле" }).min(2, {
    message: "Имя должно быть длиннее 2 символов",
  }),
})
export const FormSchema = z.object({
  email: z.string({ required_error: "Обязательное поле" }).email(),
  password: z.string({ required_error: "Обязательное поле" }).min(8, {
    message: "Пароль должен содержать минимум 8 символов",
  }),
})
const RegisterFormSchema = z.object({
  ...UsernameSchema.shape,
  ...FormSchema.shape,
})
const RegisterPage = () => {
  const navigate = useNavigate()
  const { state } = useLocation()

  const { toast } = useToast()
  const [registerUser, { isLoading, isSuccess }] = useRegisterMutation()
  const form = useForm<z.infer<typeof RegisterFormSchema>>({
    resolver: zodResolver(RegisterFormSchema),
    defaultValues: {
      username: "",
      password: "",
      email: "",
    },
  })
  const onSubmit = (values: z.infer<typeof RegisterFormSchema>) => {
    registerUser({
      username: values.email,
      email: values.email,
      password: values.password,
      fullName: values.username,
    })
  }

  useEffect(() => {
    if (isSuccess) {
      toast({ title: "Регистрация прошла успешно" })
      navigate(state)
    }
  }, [isSuccess, navigate, state, toast])
  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit)}
        className="flex-1 flex flex-col justify-between"
      >
        <div className="flex flex-col gap-6">
          <div className="flex flex-col gap-3">
            <h1 className="scroll-m-20 text-4xl font-medium">Привет!</h1>
            <p className="text-lg">
              После регистрации вы сможете взять питомца из приюта!
            </p>
          </div>
          <div className="flex flex-col gap-4">
            <FormField
              control={form.control}
              name="username"
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input placeholder="Введите ваше имя" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input placeholder="Введите вашу эл. почту" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Input type="password" placeholder="Пароль" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
        </div>
        <Button type="submit" disabled={isLoading}>
          Далее
        </Button>
      </form>
    </Form>
  )
}
export default RegisterPage
